{% extends "base.html" %}

{% block title %}AI配置 - 数据预处理系统{% endblock %}

{% block head %}
<style>
.model-item:hover {
    background-color: #f8f9fa !important;
}
.model-item.bg-light {
    background-color: #e9ecef !important;
    border-color: #007bff !important;
}
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">
                    <i class="fas fa-robot me-2"></i>AI模型配置管理
                </h4>
                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addAiConfigModal">
                    <i class="fas fa-plus me-1"></i>添加AI配置
                </button>
            </div>
            <div class="card-body">
                {% if configs %}
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">当前激活模型:</label>
                        <select class="form-select" id="activeModel">
                            <option value="">请选择激活的AI模型</option>
                            {% for name, config in configs.items() %}
                            <option value="{{ name }}" {% if name == active_model %}selected{% endif %}>
                                {{ name }} ({{ config.model_type.value }})
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-6 d-flex align-items-end">
                        <button type="button" class="btn btn-primary" onclick="setActiveModel()">
                            <i class="fas fa-check me-1"></i>设为激活
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>配置名称</th>
                                <th>模型类型</th>
                                <th>模型名称</th>
                                <th>API地址</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for name, config in configs.items() %}
                            <tr>
                                <td>
                                    <strong>{{ name }}</strong>
                                    {% if name == active_model %}
                                    <span class="badge bg-primary ms-2">激活</span>
                                    {% endif %}
                                </td>
                                <td><span class="badge bg-info">{{ config.model_type.value }}</span></td>
                                <td>{{ config.model_name }}</td>
                                <td>{{ config.api_base or '-' }}</td>
                                <td>
                                    <span class="badge bg-secondary" id="ai-status-{{ name }}">未加载</span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-success me-1" onclick="loadAiModel('{{ name }}')">
                                        <i class="fas fa-play"></i> 加载
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="removeAiConfig('{{ name }}')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="empty-state text-center py-5">
                    <i class="fas fa-robot fa-3x text-muted mb-3"></i>
                    <h5>暂无AI模型配置</h5>
                    <p class="text-muted">点击上方"添加AI配置"按钮开始配置AI模型</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 添加AI配置模态框 -->
<div class="modal fade" id="addAiConfigModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus me-2"></i>添加AI模型配置
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addAiConfigForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="aiConfigName" class="form-label">配置名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="aiConfigName" name="name" required
                                   placeholder="例如: OpenAI-GPT3.5">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="aiModelType" class="form-label">模型类型 <span class="text-danger">*</span></label>
                            <select class="form-select" id="aiModelType" name="model_type" required>
                                <option value="">请选择模型类型</option>
                                <option value="openai">OpenAI</option>
                                <option value="claude">Claude</option>
                                <option value="ollama">Ollama (本地)</option>
                                <option value="local_llm">本地模型</option>
                                <option value="baidu_wenxin">百度文心</option>
                                <option value="zhipu_glm">智谱GLM</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-10 mb-3">
                            <label for="aiModelName" class="form-label">模型名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="aiModelName" name="model_name" required
                                   placeholder="例如: gpt-3.5-turbo">
                        </div>
                        <div class="col-md-2 mb-3 ollama-models" style="display: none;">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-outline-info w-100" onclick="loadOllamaModels()">
                                <i class="fas fa-list"></i> 选择
                            </button>
                        </div>
                    </div>
                    
                    <!-- Ollama模型选择器 -->
                    <div class="row ollama-models" style="display: none;">
                        <div class="col-md-12 mb-3">
                            <label class="form-label">可用的Ollama模型:</label>
                            <div id="ollamaModelList" class="border rounded p-2" style="max-height: 150px; overflow-y: auto;">
                                <small class="text-muted">点击"选择"按钮加载模型列表</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row api-config">
                        <div class="col-md-12 mb-3">
                            <label for="aiApiKey" class="form-label">API密钥 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="aiApiKey" name="api_key"
                                   placeholder="输入API密钥">
                        </div>
                    </div>
                    
                    <div class="row api-config">
                        <div class="col-md-12 mb-3">
                            <label for="aiApiBase" class="form-label">API地址</label>
                            <input type="url" class="form-control" id="aiApiBase" name="api_base"
                                   placeholder="例如: https://api.openai.com/v1">
                        </div>
                    </div>
                    
                    <div class="row local-config" style="display: none;">
                        <div class="col-md-12 mb-3">
                            <label for="localModelPath" class="form-label">本地模型路径</label>
                            <input type="text" class="form-control" id="localModelPath" name="local_model_path"
                                   placeholder="例如: /path/to/chatglm3-6b">
                        </div>
                    </div>
                    
                    <div class="row local-config" style="display: none;">
                        <div class="col-md-6 mb-3">
                            <label for="aiDevice" class="form-label">运行设备</label>
                            <select class="form-select" id="aiDevice" name="device">
                                <option value="auto">自动选择</option>
                                <option value="cpu">CPU</option>
                                <option value="cuda">GPU (CUDA)</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="aiMaxTokens" class="form-label">最大令牌数</label>
                            <input type="number" class="form-control" id="aiMaxTokens" name="max_tokens" 
                                   placeholder="2048" value="2048" min="1" max="8192">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="aiTemperature" class="form-label">生成温度</label>
                            <input type="number" class="form-control" id="aiTemperature" name="temperature" 
                                   placeholder="0.7" value="0.7" min="0" max="2" step="0.1">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save me-1"></i>保存配置
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // 模型类型变化时显示/隐藏相关配置
    $('#aiModelType').change(function() {
        const modelType = $(this).val();
        
        if (modelType === 'local_llm') {
            $('.api-config').hide();
            $('.local-config').show();
            $('.ollama-models').hide();
            $('#aiApiKey').prop('required', false);
        } else if (modelType === 'ollama') {
            $('.api-config').show();
            $('.local-config').hide();
            $('.ollama-models').show();
            $('#aiApiKey').prop('required', false);
        } else {
            $('.api-config').show();
            $('.local-config').hide();
            $('.ollama-models').hide();
            $('#aiApiKey').prop('required', true);
        }
        
        // 设置默认值
        const defaults = {
            'openai': {
                model_name: 'gpt-3.5-turbo',
                api_base: 'https://api.openai.com/v1'
            },
            'claude': {
                model_name: 'claude-3-sonnet-20240229',
                api_base: 'https://api.anthropic.com'
            },
            'ollama': {
                model_name: 'qwen2:latest',
                api_base: 'http://localhost:11434'
            },
            'local_llm': {
                model_name: 'chatglm3-6b'
            }
        };
        
        if (defaults[modelType]) {
            $('#aiModelName').val(defaults[modelType].model_name || '');
            $('#aiApiBase').val(defaults[modelType].api_base || '');
        }
    });
    
    // 表单提交
    $('#addAiConfigForm').submit(function(e) {
        e.preventDefault();
        addAiConfig();
    });
});

function addAiConfig() {
    const formData = {
        name: $('#aiConfigName').val(),
        model_type: $('#aiModelType').val(),
        model_name: $('#aiModelName').val(),
        api_key: $('#aiApiKey').val(),
        api_base: $('#aiApiBase').val(),
        local_model_path: $('#localModelPath').val(),
        device: $('#aiDevice').val(),
        max_tokens: $('#aiMaxTokens').val(),
        temperature: $('#aiTemperature').val()
    };
    
    $.ajax({
        url: '/api/ai/configs',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData)
    })
    .done(function(data) {
        if (data.success) {
            Notification.success('AI配置添加成功');
            $('#addAiConfigModal').modal('hide');
            location.reload();
        } else {
            Notification.error('添加失败: ' + data.message);
        }
    })
    .fail(function() {
        Notification.error('添加AI配置失败');
    });
}

function loadAiModel(configName) {
    const btn = $(`button[onclick="loadAiModel('${configName}')"]`);
    const statusBadge = $(`#ai-status-${configName}`);
    
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 加载中...');
    statusBadge.removeClass().addClass('badge bg-warning').text('加载中...');
    
    $.post(`/api/ai/load/${configName}`)
        .done(function(data) {
            if (data.success) {
                statusBadge.removeClass().addClass('badge bg-success').text('已加载');
                Notification.success('AI模型加载成功');
                // 自动设为激活模型
                $('#activeModel').val(configName);
            } else {
                statusBadge.removeClass().addClass('badge bg-danger').text('加载失败');
                Notification.error('模型加载失败: ' + data.message);
            }
        })
        .fail(function() {
            statusBadge.removeClass().addClass('badge bg-danger').text('加载失败');
            Notification.error('模型加载失败');
        })
        .always(function() {
            btn.prop('disabled', false).html('<i class="fas fa-play"></i> 加载');
        });
}

function setActiveModel() {
    const modelName = $('#activeModel').val();
    if (!modelName) {
        Notification.warning('请先选择要激活的模型');
        return;
    }
    
    // TODO: 实现设置激活模型的API
    Notification.success(`已设置 ${modelName} 为激活模型`);
}

function removeAiConfig(configName) {
    if (confirm(`确定要删除AI配置"${configName}"吗？`)) {
        // TODO: 实现删除功能
        Notification.info('删除功能开发中...');
    }
}

function loadOllamaModels() {
    const apiBase = $('#aiApiBase').val() || 'http://localhost:11434';
    const listContainer = $('#ollamaModelList');
    
    listContainer.html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>');
    
    $.get('/api/ollama/models', { url: apiBase })
        .done(function(data) {
            if (data.success && data.models.length > 0) {
                let html = '';
                data.models.forEach(model => {
                    const sizeText = formatFileSize(model.size);
                    html += `
                        <div class="model-item p-2 border-bottom" style="cursor: pointer;" onclick="selectOllamaModel('${model.name}')">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <strong>${model.name}</strong>
                                    <small class="text-muted d-block">${sizeText}</small>
                                </div>
                                <i class="fas fa-chevron-right text-muted"></i>
                            </div>
                        </div>
                    `;
                });
                listContainer.html(html);
            } else {
                listContainer.html('<div class="text-muted text-center">未找到可用模型</div>');
            }
        })
        .fail(function(xhr) {
            const errorMsg = xhr.responseJSON ? xhr.responseJSON.message : '加载模型列表失败';
            listContainer.html(`<div class="text-danger text-center">${errorMsg}</div>`);
        });
}

function selectOllamaModel(modelName) {
    $('#aiModelName').val(modelName);
    Notification.success(`已选择模型: ${modelName}`);
    
    // 高亮选中的模型
    $('.model-item').removeClass('bg-light');
    $('.model-item').filter(function() {
        return $(this).find('strong').text() === modelName;
    }).addClass('bg-light');
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
</script>
{% endblock %}